"use client"
import Link from "next/link"
import { useState, useEffect } from "react"
import { useSearchParams } from 'next/navigation';
import { Suspense } from 'react';
export const dynamicParams = true // 允许动态参数
import { API_CONFIG } from "../url"

interface Agent {
  id: string
  undertaker: string
  createTime: string
  updateTime: string
  deleflag: string
  parentId: number
  personLevel: number
  uphone: string
  uidnumber: string
  upass: string | null
}

interface ApiResponse {
  total: number
  list: Agent[]
  pageNum: number
  pageSize: number
  pages: number
  isFirstPage: boolean
  isLastPage: boolean
}

function FormContent() {
  const [agents, setAgents] = useState<Agent[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(5) // 每页显示5条数据
  const [total, setTotal] = useState(0)
  const [pages, setPages] = useState(0)
  const [parentId, setParentId] = useState<string | null>(null)
  const [parentLevel, setParentLevel] = useState<string | null>(null)
  const [token, setToken] = useState<string | null>(null);

  // 搜索参数状态
  const [searchParams, setSearchParams] = useState({
    undertaker: '',
    uidnumber: '',
    uphone: ''
  });

  // 存储当前搜索条件的状态
  const [currentSearch, setCurrentSearch] = useState<{
    undertaker?: string,
    uidnumber?: string,
    uphone?: string
  } | null>(null);

  useEffect(() => {
    setToken(localStorage.getItem('token'));
  }, []);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      const tid = localStorage.getItem("tid")
      const pl = localStorage.getItem("parentLevel")
      setParentId(tid)
      setParentLevel(pl)
    }
  }, [])

  // 处理输入框变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setSearchParams(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // 获取代理数据
  // const fetchAgents = async (page: number, size: number, search?: { undertaker?: string, uidnumber?: string, uphone?: string }) => {
  //   try {
  //     setLoading(true)

  //     if (!parentId) {
  //       throw new Error("请先登录！")
  //     }
  //     const pl = localStorage.getItem("parentLevel")
  //       // 只有当 tid 不为 1 时才添加 teacherId 参数

  //     // 构建查询参数
  //     let queryParams = `parentId=${parentLevel}&currentPage=${page}&pageSize=${size}`;
  //     if (search) {
  //       if (search.undertaker) queryParams += `&undertaker=${search.undertaker}`;
  //       if (search.uidnumber) queryParams += `&uidnumber=${search.uidnumber}`;
  //       if (search.uphone) queryParams += `&uphone=${search.uphone}`;
  //       setCurrentSearch(search);
  //     } else {
  //       setCurrentSearch(null);
  //     }

  //     console.log("Fetching agents with params:", queryParams);

  //     const response = await fetch(
  //       `${API_CONFIG.BASE_URL}/api/personal/list?${queryParams}`,
  //       {
  //         method: 'GET',
  //         headers: {
  //           'Content-Type': 'application/json',
  //           'Authorization': `Bearer ${token}`
  //         },
  //         credentials: 'include',
  //       }
  //     )

  //     if (!response.ok) throw new Error("获取数据失败")

  //     const data = await response.json()
  //     console.log("API response:", data);

  //     // 处理API响应（兼容两种格式：直接数组或包含list字段的对象）
  //     if (data.list && Array.isArray(data.list)) {
  //       setAgents(data.list);
  //       setTotal(data.total || 0);
  //       setPages(data.pages || Math.ceil(data.total / size));
  //     } else if (Array.isArray(data)) {
  //       setAgents(data);
  //       setTotal(data.length);
  //       setPages(Math.ceil(data.length / size));
  //     } else {
  //       throw new Error("API返回格式不符合预期");
  //     }

  //     setCurrentPage(page);
  //   } catch (err) {
  //     setError(err instanceof Error ? err.message : "未知错误")
  //   } finally {
  //     setLoading(false)
  //   }
  // }
  const fetchAgents = async (page: number, size: number, search?: { undertaker?: string, uidnumber?: string, uphone?: string }) => {
    try {
      setLoading(true);

      if (!parentId) {
        throw new Error("请先登录！");
      }

      const pl = localStorage.getItem("parentLevel");

      // 构建查询参数
      let queryParams = `currentPage=${page}&pageSize=${size}`;

      // 只有当 parentLevel 不等于 "1" 时才添加 parentId 参数
      if (pl != "1") {
        queryParams += `&parentId=${parentId}`;
      }

      // 添加搜索条件
      if (search) {
        if (search.undertaker) queryParams += `&undertaker=${search.undertaker}`;
        if (search.uidnumber) queryParams += `&uidnumber=${search.uidnumber}`;
        if (search.uphone) queryParams += `&uphone=${search.uphone}`;
        setCurrentSearch(search);
      } else {
        setCurrentSearch(null);
      }

      console.log("Fetching agents with params:", queryParams);

      const response = await fetch(
        `${API_CONFIG.BASE_URL}/api/personal/list?${queryParams}`,
        {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          credentials: 'include',
        }
      );

      if (!response.ok) throw new Error("获取数据失败");

      const data = await response.json();
      console.log("API response:", data);

      // 处理API响应
      if (data.list && Array.isArray(data.list)) {
        setAgents(data.list);
        setTotal(data.total || 0);
        setPages(data.pages || Math.ceil(data.total / size));
      } else if (Array.isArray(data)) {
        setAgents(data);
        setTotal(data.length);
        setPages(Math.ceil(data.length / size));
      } else {
        throw new Error("API返回格式不符合预期");
      }

      setCurrentPage(page);
    } catch (err) {
      setError(err instanceof Error ? err.message : "未知错误");
    } finally {
      setLoading(false);
    }
  };


  // 页面加载时获取数据
  useEffect(() => {
    if (parentId) {
      fetchAgents(currentPage, pageSize, currentSearch);
    }
  }, [currentPage, pageSize, parentId, currentSearch])

  // 处理分页变化
  const handlePageChange = (page: number) => {
    setCurrentPage(page)
  }

  // 处理搜索
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault()
    fetchAgents(1, pageSize, searchParams);
  }

  // 重置搜索
  const handleResetSearch = () => {
    setSearchParams({ undertaker: '', uidnumber: '', uphone: '' });
    fetchAgents(1, pageSize);
  }

  // 导出
  const handleExport = async () => {
    try {
      const tid = localStorage.getItem("tid");
      if (!tid) {
        throw new Error('未找到用户ID');
      }

      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未找到认证令牌');
      }

      // 构建导出参数
      let exportParams = `parentId=${tid}`;
      if (searchParams.undertaker) exportParams += `&undertaker=${searchParams.undertaker}`;
      if (searchParams.uidnumber) exportParams += `&uidnumber=${searchParams.uidnumber}`;
      if (searchParams.uphone) exportParams += `&uphone=${searchParams.uphone}`;

      const response = await fetch(
        `${API_CONFIG.BASE_URL}/api/personal/export?${exportParams}`,
        {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
          credentials: 'include',
        }
      );

      if (!response.ok) {
        throw new Error('导出失败');
      }

      // 处理文件下载
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `代理人数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    } catch (err) {
      setError(err instanceof Error ? err.message : '导出过程中发生错误');
    }
  };

  return (
    <main className="min-h-screen bg-gray-50">
      <section className="py-4 md:py-8">
        <div className="container mx-auto px-2 sm:px-4 lg:px-6">
          <div className="bg-white rounded-lg shadow-sm overflow-hidden">
            {/* 标题和操作按钮区域 */}
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center p-4 md:p-6 border-b">
              <div className="flex flex-col md:flex-row md:items-center space-y-2 md:space-y-0 md:space-x-4 w-full md:w-auto mb-2 md:mb-0">
                <Link href={{ pathname: '/teaquery' }} passHref>
                  <button className="px-3 py-2 md:px-4 md:py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-sm md:text-base w-full md:w-auto">
                    代理人列表
                  </button>
                </Link>
                <Link
                  href={{
                    pathname: '/teaquery/dailiquery/stuquery/stuquery1',
                    query: { id: parentId }
                  }}
                  passHref
                >
                  <button
                    className="px-3 py-2 md:px-4 md:py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-sm md:text-base w-full md:w-auto"
                  >
                    查看学生列表
                  </button>
                </Link>
              </div>
              <div className="flex space-x-2 w-full md:w-auto">
                <button
                  className="px-3 py-2 md:px-4 md:py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-sm md:text-base w-full md:w-auto"
                  onClick={handleExport}
                >
                  导出Excel
                </button>
                
              </div>
            </div>
            {/* 搜索筛选区域 */}
            <div className="p-4 md:p-6 border-b">
              <h2 className="text-xl md:text-2xl font-bold text-gray-800 mb-4 md:mb-6">代理人信息查询</h2>
              <form className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6" onSubmit={handleSearch}>
                {/* 姓名搜索框 */}
                <div className="space-y-1">
                  <label className="block text-sm font-medium text-gray-700">姓名</label>
                  <div className="relative rounded-md shadow-sm">
                    <input
                      type="text"
                      name="undertaker"
                      value={searchParams.undertaker}
                      onChange={handleInputChange}
                      className="block w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm transition duration-150 ease-in-out"
                      placeholder="请输入姓名"
                    />
                  </div>
                </div>

                {/* 身份证号搜索框 */}
                <div className="space-y-1">
                  <label className="block text-sm font-medium text-gray-700">身份证号</label>
                  <div className="relative rounded-md shadow-sm">
                    <input
                      type="text"
                      name="uidnumber"
                      value={searchParams.uidnumber}
                      onChange={handleInputChange}
                      className="block w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm transition duration-150 ease-in-out"
                      placeholder="请输入身份证号"
                    />
                  </div>
                </div>

                {/* 联系电话搜索框 */}
                <div className="space-y-1">
                  <label className="block text-sm font-medium text-gray-700">联系电话</label>
                  <div className="relative rounded-md shadow-sm">
                    <input
                      type="text"
                      name="uphone"
                      value={searchParams.uphone}
                      onChange={handleInputChange}
                      className="block w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm transition duration-150 ease-in-out"
                      placeholder="请输入联系电话"
                    />
                  </div>
                </div>

                {/* 搜索和重置按钮 */}
                <div className="flex items-end space-x-3">
                  <button
                    type="submit"
                    className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 text-sm font-medium transition duration-150 ease-in-out"
                  >
                    搜索
                  </button>
                  <button
                    type="button"
                    onClick={handleResetSearch}
                    className="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 text-sm font-medium transition duration-150 ease-in-out"
                  >
                    重置
                  </button>
                </div>
              </form>
            </div>

            {/* 加载状态和错误提示 */}
            {loading && (
              <div className="p-4 text-center">加载中...</div>
            )}

            {error && (
              <div className="p-4 text-center text-red-500">{error}</div>
            )}

            {/* 数据表格 */}
            {!loading && !error && agents.length === 0 && (
              <div className="p-4 text-center text-gray-500">
                没有找到匹配的记录
              </div>
            )}

            {!loading && !error && agents.length > 0 && (
              <>
                {/* 数据表格 */}
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-gray-200">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">序号</th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">姓名</th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">身份证号</th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">联系电话</th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">代理级别</th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                      </tr>
                    </thead>
                    <tbody className="bg-white divide-y divide-gray-200">
                      {agents.map((agent, index) => (
                        <tr key={agent.id} className="hover:bg-gray-50">
                          <td className="px-4 py-2 whitespace-nowrap text-sm text-gray-500">
                            {(currentPage - 1) * pageSize + index + 1}
                          </td>
                          <td className="px-4 py-2 whitespace-nowrap text-sm font-medium text-gray-900">
                            {agent.undertaker}
                          </td>
                          <td className="px-4 py-2 whitespace-nowrap text-sm text-gray-500">
                            {agent.uidnumber}
                          </td>
                          <td className="px-4 py-2 whitespace-nowrap text-sm text-gray-500">
                            {agent.uphone}
                          </td>
                          <td className="px-4 py-2 whitespace-nowrap text-sm text-gray-500">
                            {agent.createTime}
                          </td>
                          <td className="px-4 py-2 whitespace-nowrap text-sm text-gray-500">
                            {agent.personLevel === 1 ? '总代理' :
                              agent.personLevel === 2 ? '省代理' :
                                agent.personLevel === 3 ? '市代理' :
                                  '未知级别'}
                          </td>
                          <td className="px-4 py-2 whitespace-nowrap text-sm font-medium space-x-2">
                            {parentLevel == "1" && agent.id != "1" ? (
                              <Link
                                href={{
                                  pathname: '/teaquery/dailiquery',
                                  query: {
                                    id: agent.id,
                                    undertaker: agent.undertaker,
                                    parentId: parentId || agent.parentId
                                  }
                                }}
                                className="text-blue-600 hover:text-blue-900 text-xs md:text-sm"
                                onClick={() => localStorage.setItem('sfid', agent.id)}
                              >
                                查看代理
                              </Link>
                            ) : null}
                            <Link
                              href={{
                                pathname: '/stuquery',
                                query: {
                                  id: agent.id,
                                  undertaker: agent.undertaker,
                                  parentId: parentId || agent.parentId
                                }
                              }}
                              className="text-blue-600 hover:text-blue-900 text-xs md:text-sm"
                              onClick={() => localStorage.setItem('sfid', agent.id)}
                            >
                              查看学生
                            </Link>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* 分页 */}
                <div className="px-4 py-3 bg-white border-t border-gray-200 sm:px-6">
                  <div className="flex flex-col sm:flex-row items-center justify-between">
                    <div className="text-sm text-gray-500 mb-2 sm:mb-0">
                      显示 <span className="font-medium">{(currentPage - 1) * pageSize + 1}</span> 到{' '}
                      <span className="font-medium">{Math.min(currentPage * pageSize, total)}</span> 条，共{' '}
                      <span className="font-medium">{total}</span> 条记录
                    </div>
                    <div className="flex space-x-1">
                      <button
                        className="px-3 py-1 border rounded-md text-sm disabled:opacity-50 bg-white text-gray-700 hover:bg-gray-50"
                        disabled={currentPage === 1}
                        onClick={() => handlePageChange(currentPage - 1)}
                      >
                        上一页
                      </button>
                      {Array.from({ length: Math.min(pages, 5) }, (_, i) => {
                        let pageNum = i + 1
                        if (pages > 5) {
                          if (currentPage <= 3) {
                            pageNum = i + 1
                          } else if (currentPage >= pages - 2) {
                            pageNum = pages - 4 + i
                          } else {
                            pageNum = currentPage - 2 + i
                          }
                        }
                        return (
                          <button
                            key={pageNum}
                            className={`px-3 py-1 border rounded-md text-sm ${currentPage === pageNum
                              ? 'bg-blue-600 text-white'
                              : 'bg-white text-gray-700 hover:bg-gray-50'
                              }`}
                            onClick={() => handlePageChange(pageNum)}
                          >
                            {pageNum}
                          </button>
                        )
                      })}
                      <button
                        className="px-3 py-1 border rounded-md text-sm bg-white text-gray-700 hover:bg-gray-50"
                        disabled={currentPage === pages}
                        onClick={() => handlePageChange(currentPage + 1)}
                      >
                        下一页
                      </button>
                    </div>
                  </div>
                </div>
              </>
            )}
          </div>
        </div>
      </section>
    </main>
  )
}

export default function CertificatesPage() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <FormContent />
    </Suspense>
  );
}